//WL_ERROR.CPP

/*
=============================================================================

                             ERROR HANDLING

=============================================================================
*/

#include "wl_error.h"
#include "wl_def.h"
#include "version.h"

#include <fstream>
#include <iostream>
#include <stack>

cMessageHandler msgHandler;

/*
//Class Ctor
cMessageHandler::cMessageHandler(void)
{
    //...
}

//Class Dtor
cMessageHandler::~cMessageHandler(void)
{
    //...
}
*/

//Store an error in the stack. const char* is used for compatibility
//with existing error functions in the engine.
void cMessageHandler::StoreMsg(const char *msg)
{
    //Push msg onto the stack
    msgStack.push(msg);
}

void cMessageHandler::LogMessage(std::string msg, int level = 0)
{
    std::string msgTemp;

    if(level == 0)
    {
        msgTemp = "[MESSAGE]";
    }
    else if(level == 1)
    {
        msgTemp = "[WARNING]";
    }
    else if(level == 2)
    {
        msgTemp = "[SEVERE]";
    }
    //Push msg onto the stack
    msgTemp += msg;
    msgStack.push(msgTemp.c_str());
}

//Print the contents of errorStack to a log file.
void cMessageHandler::PrintLog(void)
{
    std::ofstream logFile;

    logFile.open ("canis_log.txt", std::ios::out);

    logFile<<"CanisSDL Version: "<< c_major << "." << c_minor << "." << c_patch << "-" << c_revision << "  " << c_release << " " << c_major_name << "\n\n\n";

    while(msgStack.size() != 0)
    {
        logFile<<"--- "<<msgStack.top() << "\n";
        msgStack.pop();
    };

    logFile.close();
}


//Trimmed down Quit() function without all of the preprocessor
//conditional logic related to NOTYET. Now stores the given error in
//the message stack and creates and fills the log file on exit.
void Quit (const char *errorStr, ...)
{
    //Store the error to the stack
    msgHandler.StoreMsg(errorStr);
    msgHandler.LogMessage("DERP DERP DERP!!!");

    char error[256];
    if(errorStr != NULL)
    {
        va_list vlist;
        va_start(vlist, errorStr);
        vsprintf(error, errorStr, vlist);
        va_end(vlist);
    }
    else error[0] = 0;

    if (!pictable)  // don't try to display the red box before it's loaded
    {
        ShutdownId();
        if (error && *error)
        {
            puts(error);
            VW_WaitVBL(100);
        }

        msgHandler.PrintLog();
        exit(1);
    }

    if (!error || !*error)
    {
        WriteConfig ();
    }

    ShutdownId ();

    if (error && *error)
    {
        puts(error);
        VW_WaitVBL(200);
        exit(1);
    }

    msgHandler.PrintLog();
    exit(0);
}
